package com.emm.yixun.website.controller.customer;
//框架包
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.emm.yixun.common.model.CustTagInfo;
import com.emm.yixun.common.model.Customer;
//变化的引用
import com.emm.yixun.common.model.CustomerProjectQuestion;
import com.emm.yixun.common.model.CustomerProjectQuestionInfo;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.Tag;
import com.emm.yixun.common.model.TagInfo;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.CustTagDto;
import com.emm.yixun.common.model.dto.CustomerProjectQuestionDto;
import com.emm.yixun.common.model.dto.ProjectDto;
import com.emm.yixun.common.model.dto.TagDto;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.IsAvlidEnum;
import com.emm.yixun.common.page.Page;
//common
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.customer.service.CustTagServiceFacade;
import com.emm.yixun.customer.service.CustomerProjectQuestionServiceFacade;
import com.emm.yixun.customer.service.CustomerServiceFacade;
import com.emm.yixun.customer.service.ProjectQuestionnaireServiceFacade;
import com.emm.yixun.customer.service.TagServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
//website
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;




@Controller
@RequestMapping("/customer/customerProjectQuestion/")
public class CustomerProjectQuestionController extends BaseController<CustomerProjectQuestion>{
	
	@Autowired
	private CustomerProjectQuestionServiceFacade customerProjectQuestionServiceFacade;
	@Autowired
    private CustomerServiceFacade customerServiceFacade;
	@Autowired
    private ProjectServiceFacade projectServiceFacade;
	@Autowired
    private TagServiceFacade tagServiceFacade;
	@Autowired
    private CustTagServiceFacade custTagServiceFacade;
	
	@RequestMapping(value="index")
	public String index(ModelMap map){
		if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			//查询菜单按钮权限
			map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));		
			return "/customer/customerProjectQuestion/list";
		}
		return Const.NO_AUTHORIZED_URL;
	}
	
	//新增返回实体对象
	@RequestMapping(value="add", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  add(CustomerProjectQuestionDto dto){
    	AjaxRes ar=getAjaxRes();
    	
    	/*
    	 *1.判断权限 
    	 *2.调用新增接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:customerProjectQuestion:add"))){
        	try {
        		User user=ShiroUtil.getCurrentUser();
        		dto.setMerchantId(user.getMerchantId());
        		dto.setCreateUser(user.getId());
        		dto.setDelFlag("0");
        		dto.setUpdateUser(user.getId());
        		dto.setUpdateTime(new Date());
				Response<CustomerProjectQuestionDto> response=customerProjectQuestionServiceFacade.save(dto);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				}else{
					ar.setFailMsg(Const.SAVE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
    	}
    	return ar;
    }
	//查看
	@RequestMapping(value="view", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  view(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:customerProjectQuestion:view"))){
        	try {
				Response<CustomerProjectQuestion> response=customerProjectQuestionServiceFacade.findById(id);
				if(response.isSuccess()){
					ar.setSucceed(response.getEntity());
				}else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	}
    	return ar;
    }
	
	//修改
	@RequestMapping(value="edit", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  edit(CustomerProjectQuestionDto dto){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用修改接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:customerProjectQuestion:edit"))){
        	try {
        		Response<Integer> response=customerProjectQuestionServiceFacade.updateByPrimaryKey(dto, true);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				}else{
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
    	}
    	return ar;
    }
	
	//删除
	@RequestMapping(value="delete", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  delete(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:customerProjectQuestion:delete"))){
        	try {
        		Response<Integer> response=customerProjectQuestionServiceFacade.deleteByPrimaryKey(id);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				}else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
    	}
    	return ar;
    }
	
	
	
	//分页查询
	@RequestMapping(value="list", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  list(CustomerProjectQuestionDto dto,Integer pageSize,Integer pageNum){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用分页查询接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:customerProjectQuestion:list"))){
        	try {
        		Page<CustomerProjectQuestion> response=customerProjectQuestionServiceFacade.findPageByDto(dto, PageUtil.begin(pageNum, pageSize),pageSize);
                if(response.getSuccess()){
                    if(null==response.getRows())response.setRows(new ArrayList<CustomerProjectQuestion>());
                	response.setPageNumber(pageNum);
                	ar.setSucceed(response);
                }else{
                	ar.setFailMsg(Const.DATA_FAIL);
                }
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	}
    	return ar;
    }
	
	//客户问卷-查询
	@RequestMapping(value="questionList", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes questionList(HttpServletRequest request){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用分页查询接口
    	 *3.返回信息
    	*/
        //if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:projectQuestion:list"))){
        	try {
        		String customerId = request.getParameter("customerId");
        		String projectQuestionnaireId = request.getParameter("questionnaireId");
        		String level = request.getParameter("level");
        		String problemCode = request.getParameter("problemCode");
        		String customerPhone = request.getParameter("customerPhone");
        		
        		CustomerProjectQuestionDto dto = new CustomerProjectQuestionDto();
        		dto.setCustomerId(Long.parseLong(customerId));
        		dto.setProjectQuestionnaireId(Long.parseLong(projectQuestionnaireId));
        		//问题等级
        		if(StringUtils.isNotBlank(level)){
        			dto.setLevel(Long.parseLong(level));
        		}
        		//问题编号
        		if(StringUtils.isNotBlank(problemCode)){
        			dto.setProblemCode(problemCode);
        		}
        		//未匹配的客户手机号
        		if("-1".equals(customerId) && StringUtils.isNotBlank(customerPhone)) {
        			dto.setCustomerPhone(customerPhone);
        		}
        		dto.setIsValid(IsAvlidEnum.AVILD.getNo());
    			dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        		ResponseList<CustomerProjectQuestionInfo> response = customerProjectQuestionServiceFacade.questionList(dto);
        		if(response.isSuccess()){
                    if(null==response.getEntity())response.setEntity(new ArrayList<CustomerProjectQuestionInfo>());
                	ar.setSucceed(response);
                }else{
                	ar.setFailMsg(Const.DATA_FAIL);
                }
        		
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	//}
    	return ar;
    }
	
	@RequestMapping(value="toCusTagPage")
    public String toCusTagPage(HttpServletRequest request, ModelMap map){
	    String customerId = request.getParameter("customerId");
	    map.addAttribute("customerId", customerId);
	    
        String projectId = request.getParameter("projectId");
        map.addAttribute("projectId", projectId);
        
        Response<Customer> cus = customerServiceFacade.findById(Long.parseLong(customerId));
        map.addAttribute("customer", cus.getEntity());
        
        Response<Project> project = projectServiceFacade.findById(Long.parseLong(projectId));
        map.addAttribute("project", project.getEntity());
        
        TagDto dto = new TagDto();
        dto.setParentId(0L);
        dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        ResponseList<Tag> res = tagServiceFacade.findByDto(dto);
        if(res.isSuccess()){
            map.addAttribute("tagList", res.getEntity());
        }
        
	    return "/customer/questionnaire/survey";
    }
	
	//客户标签问卷-查询
    @RequestMapping(value="cusTagQuestionList", method=RequestMethod.POST)
    @ResponseBody
    public AjaxRes cusTagQuestionList(HttpServletRequest request, Integer pageNum, Integer pageSize){
        AjaxRes ar=getAjaxRes();
        /*
         *1.判断权限 
         *2.调用分页查询接口
         *3.返回信息
        */
        //if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:projectQuestion:list"))){
            try {
                String customerId = request.getParameter("customerId");
                String projectId = request.getParameter("projectId");
                
                CustomerProjectQuestionDto dto = new CustomerProjectQuestionDto();
                dto.setCustomerId(Long.parseLong(customerId));
                dto.setProjectId(Long.parseLong(projectId));
                dto.setIsValid(IsAvlidEnum.AVILD.getNo());
                dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
                Page<CustomerProjectQuestionInfo> response = customerProjectQuestionServiceFacade
                        .cusTagPageByDto(dto, PageUtil.begin(pageNum, pageSize),pageSize);
                if(response.getSuccess()){
                    if(null==response.getRows())response.setRows(new ArrayList<CustomerProjectQuestionInfo>());
                    response.setPageNumber(pageNum);
                    ar.setSucceed(response);
                }else{
                    ar.setFailMsg(Const.DATA_FAIL);
                }
                
            } catch (Exception e) {
                logger.error(e.toString(),e);
                ar.setFailMsg(Const.DATA_FAIL);
            }
        //}
        return ar;
    }
    
    @RequestMapping(value="addCusTag")
    public String addCusTag(String cusTagIds, String custId, String type, 
            Long customerId, ModelMap map){
        map.put("cusTagIds", cusTagIds);
        map.put("customerId", customerId);
        map.put("custId", custId);
        map.put("type", type);
        return "/customer/questionnaire/addCusTag";
    }
    
    /**
     * 查询客户标签列表
     * @param request
     * @param ids 
     * @return
     */
    @RequestMapping(value="getTagQuestionAnswerList", method=RequestMethod.POST)
    @ResponseBody
    public AjaxRes queryTagQuestionList(HttpServletRequest request, String ids){
        AjaxRes ar=getAjaxRes();
        try {
            //查询对应ID的 标签问题
            if(StringUtils.isNotBlank(ids)){
                ids = ids.replace("["," ext.id in (").replace("]",")");
            }
            TagDto dto = new TagDto();
            dto.setSql(ids);
            dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
            dto.addAsc("ext.id");
            ResponseList<TagInfo> response = tagServiceFacade.getTagQuestionAnswerList(dto);
            if(response.isSuccess()){
                if(null==response.getEntity()){
                    response.setEntity(new ArrayList<TagInfo>());
                }
                ar.setSucceed(response);
            }else{
                ar.setFailMsg(Const.DATA_FAIL);
            }
            
        } catch (Exception e) {
            logger.error(e.toString(),e);
            ar.setFailMsg(Const.DATA_FAIL);
        }
        return ar;
    }
    
    /**
     * 查询客户标签列表
     * @param request
     * @param ids 
     * @return
     */
    @RequestMapping(value="saveCusTag", method=RequestMethod.POST)
    @ResponseBody
    public AjaxRes saveCusTag(HttpServletRequest request){
        AjaxRes ar=getAjaxRes();
        try {
            //客户ID
            String customerId = request.getParameter("customerId");
            //问题集合
            String json = request.getParameter("json");
            //获取用户
            User user = ShiroUtil.getCurrentUser();
            if(user == null){
                ar.setFailMsg(Const.SAVE_FAIL);
                return ar;
            }
            
            CustTagDto dto = new CustTagDto();
            dto.setCustomerId(Long.parseLong(customerId));
            dto.setAgentId(user.getId().toString());
            dto.setCreateUser(user.getId());
            dto.setUpdateUser(user.getId());
            Response<CustTagDto> response = custTagServiceFacade.saveCusTag(dto, json);
            if(response.isSuccess()){
                ar.setSucceedMsg(Const.SAVE_SUCCEED);
            }else{
                ar.setFailMsg(Const.SAVE_FAIL);
            }
        } catch (Exception e) {
            logger.error(e.toString(),e);
            ar.setFailMsg(Const.DATA_FAIL);
        }
        return ar;
    }
    
    /**
     * 查询客户问卷标签库
     * @param request
     * @param typeId 标签分组ID
     * @param tagName 问题内容
     * @return
     */
    @RequestMapping(value="queryCusTagList", method=RequestMethod.POST)
    @ResponseBody
    public AjaxRes queryCusTag(HttpServletRequest request, Integer pageSize,Integer pageNum){
        AjaxRes ar=getAjaxRes();
        try { 
            String customerId = request.getParameter("customerId");
            String tagId = request.getParameter("tagId");
            String tagName = request.getParameter("tagName");
            
            CustTagDto dto = new CustTagDto();
            dto.setCustomerId(Long.parseLong(customerId));
            dto.setParentId(tagId);
            dto.setTagName(tagName);
            dto.addDesc("t.create_time");
            Page<CustTagInfo> response = custTagServiceFacade.findPageByDto(dto, PageUtil.begin(pageNum, pageSize), pageSize);
            if(response.getSuccess()){
                if(null==response.getRows()) {
                    response.setRows(new ArrayList<CustTagInfo>());
                }
                response.setPageNumber(pageNum);
                ar.setSucceed(response);
            }else{
                ar.setFailMsg(Const.DATA_FAIL);
            }
        } catch (Exception e) {
            logger.error(e.toString(),e);
            ar.setFailMsg(Const.DATA_FAIL);
        }
        return ar;
    }
    
    /**
    * 删除客户标签
    * @param request
    * @return
    */
    @RequestMapping(value="delCusTag", method=RequestMethod.POST)
    @ResponseBody
    public AjaxRes delCusTag(HttpServletRequest request, Long id){
        AjaxRes ar=getAjaxRes();
        try { 
            if(id == null){
                ar.setFailMsg(Const.SAVE_FAIL);
                return ar;
            }
            Response<Integer> response = custTagServiceFacade.deleteByPrimaryKey(id);
            if(response.isSuccess()){
                ar.setSucceedMsg(Const.SAVE_SUCCEED);
            }else{
                ar.setFailMsg(Const.SAVE_FAIL);
            }
        } catch (Exception e) {
            logger.error(e.toString(),e);
            ar.setFailMsg(Const.DATA_FAIL);
        }
        return ar;
    }
    
    /**
     * 修改客户标签
     * @param request
     * @return
     */
     @RequestMapping(value="editCusTag", method=RequestMethod.POST)
     @ResponseBody
     public AjaxRes editCusTag(HttpServletRequest request, Long id){
         AjaxRes ar=getAjaxRes();
         try { 
             if(id == null){
                 ar.setFailMsg(Const.SAVE_FAIL);
                 return ar;
             }
             String json = request.getParameter("json");
             CustTagDto dto = new CustTagDto();
             dto.setId(id);
             Response<Integer> response = custTagServiceFacade.editCusTag(dto, json);
             if(response.isSuccess()){
                 ar.setSucceedMsg(Const.SAVE_SUCCEED);
             }else{
                 ar.setFailMsg(Const.SAVE_FAIL);
             }
         } catch (Exception e) {
             logger.error(e.toString(),e);
             ar.setFailMsg(Const.DATA_FAIL);
         }
         return ar;
     }
     
     @RequestMapping(value="toCusTagList")
     public String toCusTagList(ModelMap map){
         //if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
             //判断是否拥有项目列表【全部】权限
             map.put("permitBtn", doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:list:all"));    
             //查询项目
             User user=ShiroUtil.getCurrentUser();
             ProjectDto entity = new ProjectDto();
             entity.setMerchantId(user.getMerchantId());
             entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
             entity.setResourcesCode("menu_0003_0001");
             entity.setPermissionUserId(user.getId());
             ResponseList<Project> res = projectServiceFacade.findByDto(entity);
             List<Project> projectList = new ArrayList<Project>();
             if(res.isSuccess() && null != res.getEntity() && res.getEntity().size() > 0){
                 projectList = res.getEntity();
             }
             map.addAttribute("projectList", projectList);
             return "/customer/questionnaire/cusTaglist";
         //}
         //return Const.NO_AUTHORIZED_URL;
     }
     
     /**
      * 查询客户问卷标签库
      * @param request
      * @param typeId 标签分组ID
      * @param tagName 问题内容
      * @return
      */
     @RequestMapping(value="cusTagList", method=RequestMethod.POST)
     @ResponseBody
     public AjaxRes cusTagList(HttpServletRequest request, Integer pageSize,Integer pageNum){
         AjaxRes ar=getAjaxRes();
         try {
             //获取用户
             User user = ShiroUtil.getCurrentUser();
             if(user == null){
                 ar.setFailMsg(Const.SAVE_FAIL);
                 return ar;
             }
             
             //项目ID
             String projectId = request.getParameter("projectId");
             //经纪人姓名
             String agentName = request.getParameter("agentName");
             //客户姓名
             String cusName = request.getParameter("cusName");
             //创建时间
             String startCreateTime = request.getParameter("startCreateTime");
             String endCreateTime = request.getParameter("endCreateTime");
             //修改时间
             String startUpdateTime = request.getParameter("startUpdateTime");
             String endUpdateTime = request.getParameter("endUpdateTime");
             
             CustTagDto dto = new CustTagDto();
             dto.setMerchantId(user.getMerchantId());
             dto.setProjectId(StringUtils.isNotBlank(projectId)? Long.parseLong(projectId): null);
             dto.setCusName(cusName);
             dto.setAgentName(agentName);
             dto.setCreateTimeBefore(startDate(startCreateTime));
             dto.setCreateTimeAfter(endDate(endCreateTime));
             dto.setUpdateTimeBefore(startDate(startUpdateTime));
             dto.setUpdateTimeAfter(endDate(endUpdateTime));
             Page<CustTagInfo> page = custTagServiceFacade
                     .getCusTagInfoPage(dto, PageUtil.begin(pageNum, pageSize), pageSize);
             if(page.getSuccess()){
                 if(null==page.getRows()) {
                     page.setRows(new ArrayList<CustTagInfo>());
                 }
                 page.setPageNumber(pageNum);
                 ar.setSucceed(page);
             }else{
                 ar.setFailMsg(Const.DATA_FAIL);
             }
         } catch (Exception e) {
             logger.error(e.toString(),e);
             ar.setFailMsg(Const.DATA_FAIL);
         }
         return ar;
     }
     
     private Date startDate(String startTime){
         if(StringUtils.isBlank(startTime)){
             return null;
         }
         startTime = startTime + " 00:00:00";
         return DateUtils.StringToDate(startTime, DateStyle.YYYY_MM_DD_HH_MM_SS);
     }
     private Date endDate(String endTime){
         if(StringUtils.isBlank(endTime)){
             return null;
         }
         endTime = endTime + " 23:59:59";
         return DateUtils.StringToDate(endTime, DateStyle.YYYY_MM_DD_HH_MM_SS);
     }
}
